#include "Key.h"

KeyState g_key_state = KEY_RELEASE;

static uint8_t Init_Key(void)
{
    GPIO_InitTypeDef GPIO_InitStruct = {0};

    /*Configure GPIO pin : PtPin */
    GPIO_InitStruct.Pin = KEY_Pin;
    GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
    GPIO_InitStruct.Pull = GPIO_PULLUP;
    HAL_GPIO_Init(KEY_GPIO_Port, &GPIO_InitStruct);

    return 0;
}

static KeyState Get_Key_State(void)
{
    return HAL_GPIO_ReadPin(KEY_GPIO_Port, KEY_Pin);
}

/// @brief Handles the key state machine, including initialization and key press/release detection.
/// @param None
void key_task_handler(void)
{
    static uint8_t key_task_state = 0;
    static uint8_t current_key_pin_state = KEY_RELEASE;

    if (key_task_state == 0)
    {
        if (Init_Key() == 0)
        {
            key_task_state = 1;
        }
    }
    else
    {
        current_key_pin_state = Get_Key_State();
        if (current_key_pin_state == KEY_PRESSING)// Pressed
        {
            if (g_key_state == KEY_RELEASE) // Just pressed
            {
                HAL_Delay(KEY_FILTER_TIME); // Debounce delay
                if (Get_Key_State() == KEY_PRESSING) // Check again after delay
                {
                    g_key_state = KEY_PRESSING;
                }
                else // Not pressed
                {
                    g_key_state = KEY_RELEASE;
                }
            }
        }
        else // Released
        {
            if (g_key_state == KEY_PRESSING) // Just released
            {
                g_key_state = KEY_RELEASE;
            }
        }   
    }
}